﻿using System;
using System.Windows;
using System.Windows.Navigation;
using System.Collections.Generic;
using Microsoft.Phone.Shell;
using LuyenThiVer03.DapAnWebService;
using LuyenThiVer03.GoiCauHoiWebService;

namespace LuyenThiVer03
{

    public partial class PageSoCauOnThi
    {
        private CustomBox _cusBox = new CustomBox();

        private int MucKienThucID { get; set; }
        private int TongSoCau { get; set; }
        private int CauHoiDaLoad { get; set; }
        private int MaTranKienThucID { get; set; }

        public PageSoCauOnThi()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            MucKienThucID = Convert.ToInt32(NavigationContext.QueryString["MucKienThucID"]);
            TongSoCau = Convert.ToInt32(NavigationContext.QueryString["SoCau"]);

            if (TongSoCau == 0)
            {
                MessageBox.Show("Chuyên đề này hiện tại không có câu hỏi nào. Mời bạn vui lòng chọn lại.");
                NavigationService.GoBack();
            }
            else
            {
                if (TongSoCau < 10)
                {
                    var d = MessageBox.Show("Dạng đề thi này có " + TongSoCau + " câu hỏi. Bạn có muốn làm thử không?", "", MessageBoxButton.OKCancel);

                    if (d == MessageBoxResult.OK)
                    {
                        LoadCauHoiOnThi(MucKienThucID);
                    }
                    else
                    {
                        NavigationService.GoBack();
                    }
                }
                else if (TongSoCau < 20)
                {
                    bt20.IsEnabled = false;
                    bt30.IsEnabled = false;
                    bt50.IsEnabled = false;
                }
                else if (TongSoCau < 30)
                {
                    bt30.IsEnabled = false;
                    bt50.IsEnabled = false;
                }
                else if (TongSoCau < 50)
                {
                    bt50.IsEnabled = false;
                }
            }

        }

        private void LoadCauHoiOnThi(int mucKienThucId)
        {
            //on thi
            var cauHoiWebServiceSoapClient = new GoiCauHoiWebServiceSoapClient();
            cauHoiWebServiceSoapClient.SelectAllByMucKienThuc_IDCompleted += goiCauHoi_OnSelectAllByMucKienThuc_IDCompleted;
            cauHoiWebServiceSoapClient.SelectAllByMucKienThuc_IDAsync(mucKienThucId);
        }

        private void goiCauHoi_OnSelectAllByMucKienThuc_IDCompleted(object sender, GoiCauHoiWebService.SelectAllByMucKienThuc_IDCompletedEventArgs e)
        {
            //on thi
            var listCauHoi = new List<GoiCauHoiEntity>(e.Result);
            RandomCauHoiOnThi(TongSoCau, listCauHoi);
        }

        private void RandomCauHoiOnThi(int soCau, List<GoiCauHoiEntity> listCauHoi)
        {
            //on thi
            var listCauChon = new List<GoiCauHoiEntity>();
            var count = listCauHoi.Count;
            var random = new Random();
            while (listCauChon.Count < soCau)
            {
                var nowNumber = random.Next(1, count);
                var cauHoiEntity = listCauHoi[nowNumber];
                MaTranKienThucID = cauHoiEntity.MaTranKienThuc_ID;
                if (listCauChon.Contains(cauHoiEntity))
                {
                    listCauChon.Remove(cauHoiEntity);
                }
                else
                {
                    listCauChon.Add(cauHoiEntity);
                }
            }
            LoadToanBoDapAn(listCauChon);
        }

        private void LoadToanBoDapAn(IEnumerable<GoiCauHoiEntity> listCauHoi)
        {
            //on thi
            foreach (var t in listCauHoi)
            {
                var cauhoiid = t.CauHoi_ID;
                ((App)Application.Current).ListKeyCauHoi.Add(cauhoiid);
                ((App)Application.Current).DicCauHoi.Add(cauhoiid, t.NoiDung);
                LoadDapAnMotCauHoi(cauhoiid);
            }
        }

        private void LoadDapAnMotCauHoi(long cauHoiId)
        {
            //thi thu + on thi
            var dapAnWebServiceSoapClient = new DapAnWebServiceSoapClient();
            dapAnWebServiceSoapClient.SelectAllByCauHoi_IDCompleted += DapAnWebSv_OnSelectAllByCauHoi_IDCompleted;
            dapAnWebServiceSoapClient.SelectAllByCauHoi_IDAsync(cauHoiId);
        }

        private void DapAnWebSv_OnSelectAllByCauHoi_IDCompleted(object sender, SelectAllByCauHoi_IDCompletedEventArgs e)
        {
            //thi thu +on thi
            var result = new List<DapAnEntity>(e.Result);
            var arrayDapAn = new List<string>();
            for (var i = 0; i < result.Count; i++)
            {
                //them noi dung dap an de thi thu
                arrayDapAn.Add(result[i].NoiDung);
                if (result[i].IsDapAnDung)
                {
                    ((App)Application.Current).ListDapAnDung.Add(i);
                }
            }
            //((App) Application.Current).DicKeyDapAn.Add(result[0].CauHoi_ID, arrayKeyDapAn);
            ((App)Application.Current).DicDapAn.Add(result[0].CauHoi_ID, arrayDapAn);
            ((App)Application.Current).ListDapAnUser.Add(new PageLamBaiTracNghiem.DapAnUser(10));
            CauHoiDaLoad++;
            _cusBox.progressBar.Value += 2;
            _cusBox.tblDangTai.Text = (CauHoiDaLoad * 100) / TongSoCau + " %";
            if (CauHoiDaLoad < TongSoCau) return;
            SystemTray.GetProgressIndicator(this).IsVisible = false;
            _cusBox.tblSoCau.Text = "Tổng số câu: " + Convert.ToString(TongSoCau);
            _cusBox.btBatDau.Visibility = Visibility.Visible;
            _cusBox.btBatDau.Click += btBatDau_OnClick;
        }

        private void btBatDau_OnClick(object sender, RoutedEventArgs e)
        {
            _cusBox.Close();
            NavigationService.Navigate(new Uri("/PageLamBaiTracNghiem.xaml?tongsocau=" + TongSoCau + "&kieuthi=onthi" + "&MTKT=" + MaTranKienThucID, UriKind.Relative));
        }

        private void bt10_OnClick(object sender, RoutedEventArgs e)
        {
            TongSoCau = 10;
            HandleButtonSoCauHoi(TongSoCau);
        }

        private void bt20_OnClick(object sender, RoutedEventArgs e)
        {
            TongSoCau = 20;
            HandleButtonSoCauHoi(TongSoCau);
        }

        private void bt30_OnClick(object sender, RoutedEventArgs e)
        {
            TongSoCau = 30;
            HandleButtonSoCauHoi(TongSoCau);
        }

        private void bt50_OnClick(object sender, RoutedEventArgs e)
        {
            TongSoCau = 50;
            HandleButtonSoCauHoi(TongSoCau);
        }

        private void HandleButtonSoCauHoi(int tongSoCau)
        {
            var m = MessageBox.Show("Bạn chọn ôn thi " + tongSoCau + " câu hỏi?", "", MessageBoxButton.OKCancel);
            if (m == MessageBoxResult.Cancel)
            {
                return;
            }
            LoadCauHoiOnThi(MucKienThucID);
            var progress = new ProgressIndicator { IsIndeterminate = true, IsVisible = true, Value = 30, Text = "Đang tải ..." };
            SystemTray.SetProgressIndicator(this, progress);
            _cusBox = new CustomBox
            {
                tblMonThi = { Text = "Môn : " + GetTenMonHoc(NavigationContext.QueryString["mon"]) },
                tblSoCau = { Text = "Số câu: " + tongSoCau },
                tblThoiGian = { Visibility = Visibility.Collapsed },
                progressBar = {Maximum = TongSoCau}
            };
            _cusBox.Show();
        }

        private string GetTenMonHoc(string maMonHoc)
        {
            var tenMonHoc = "";
            switch (maMonHoc)
            {
                case "76":
                    tenMonHoc = "Lý";
                    break;
                case "75":
                    tenMonHoc = "Hóa";
                    break;
                case "61":
                    tenMonHoc = "Anh";
                    break;
                case "74":
                    tenMonHoc = "Sinh";
                    break;
            }
            return tenMonHoc;
        }
    }
}